<?php
namespace App\Http\Controllers;

use App\Jobs\SendCustomMessage;
use App\Third\WXBizMsgCrypt;
use App\Third\XcxCustom;
use Illuminate\Http\Request;


class CustommsgController extends Controller {

    public function __construct(Request $request) {

    }
    public function getServer(Request $request) {
        if($this->checkSignature(
            $request->input('signature'),
            $request->input('timestamp'),
            $request->input('nonce'))) {
            return $request->input('echostr');
        }

        return 'fail';
    }

    public function postServer(Request $request) {
        $wxcpt = new WXBizMsgCrypt(
            config('xcx.kefu_token'),
            config('xcx.kefu_encodingAESKey'),
            config('xcx.appid')
        );
        // 需要返回的明文
        $sMsg = "";

        $errCode = $wxcpt->DecryptMsg(
            $request->msg_signature,
            $request->timestamp,
            $request->nonce,
            $request->getContent(),
            $sMsg
        );

        if ($errCode == 0) {
            $data = json_decode ( $sMsg);
            if ($data->MsgType == 'event') {
                $word = "亲，感谢您对「共享图书与知识」的支持, 欢迎留下您的宝贵意见!";
                $xcxCustom = new XcxCustom();
                $xcxCustom->reply($data->FromUserName, $word);
//                $job = new SendCustomMessage(
//                    0,
//                    $data->FromUserName,
//                    'text',
//                    $data->CreateTime.$data->FromUserName,
//                    $data->CreateTime,
//                    '用户会话来源：'.$data->SessionFrom,
//                    '',
//                    $this->type
//                );
//                dispatch($job);
            } elseif ($data->MsgType == 'image') {
                //客服队列
                $job = new SendCustomMessage(
                    0,
                    $data->FromUserName,
                    $data->MsgType,
                    $data->MsgId,
                    $data->CreateTime,
                    '',
                    $data->PicUrl
                );
                dispatch($job);
            } else {
//                $this->msg2qiyehaoText($data->FromUserName, $data->Content);
//                客服队列
                $job = new SendCustomMessage(
                    0,
                    $data->FromUserName,
                    $data->MsgType,
                    $data->MsgId,
                    $data->CreateTime,
                    $data->Content,
                    ''
                );
                dispatch($job);
            }
        }
        return 'success';
    }

    private function checkSignature($signature, $timestamp, $nonce) {
        $tmpArr = array(config('xcx.kefu_token'), $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}